<template>
	<el-upload
		v-model:file-list="fileList"
		style="width:100%;"
		:id="setUploadId"
		ref="uploadRef"
		:class="setClass()"
		:action="action_url"
		:multiple="multiple"
		:limit="limit"
		:list-type="listType"
		:accept="accept"
		:auto-upload="autoUpload"
		:on-progress="handleProgress"
		:on-exceed="handleExceed"
		:on-preview="handlePreview"
		:on-remove="handleRemove"
		:on-success="handleAvatarSuccess"
		:before-upload="beforeAvatarUpload"
		drag
		name="file"
	>
		<el-button type="default" :icon="Plus" v-if="btnName != ''">{{ btnName }}  ({{fileList.length}}/{{limit}})</el-button>
		<el-icon v-if="btnName == ''"><Plus /></el-icon>
	</el-upload>
	<el-dialog v-model="dialogVisible">
		<img w-full style="max-width: 100%;" :src="dialogImageUrl" />
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import store from '@/store'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile, UploadInstance, UploadFile, UploadFiles } from 'element-plus'
import { BASE_URL_REQUEST, BASS_UPLOADURL } from '@/config/index'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const uploadRef = ref<UploadInstance>()
const action_url = BASE_URL_REQUEST + BASS_UPLOADURL
const prop = defineProps({
	modelValue:{
		type: Array
	},
	btnName: {
		type: String,
		default: '点击上传图片'
	},
	backProp: {
		type: String,
		default: ''
	},
	multiple: {
		type: Boolean,
		default: false
	},
	autoUpload: {
		type: Boolean,
		default: true
	},
	small: {
		type: Boolean,
		default: false
	},
	limit: {
		type: Number,
		default: 1
	},
	listType: {
		type: String,
		default: 'picture'
	},
	accept: {
		type: String,
		default: 'image/*'
	},
	capture: {
		type: String,
		default: ''
	}
})
const setUploadId = computed(() => {
	return 'upload' + Math.floor(Math.random()*100000000000+10)
})
const emit = defineEmits(['callback', 'removeFile', 'chooseFile', 'update:modelValue'])
onMounted(() => {
	console.log('单图上传组件加载初始化完成');
	setList(prop.modelValue)
	if(prop.capture){
		nextTick(() => {
			document.getElementById(setUploadId.value)?.querySelector('.el-upload__input')?.setAttribute('capture',prop.capture)
		})
	}
})
const setClass = () => {
	let className = (prop.btnName == '' && fileList.value.length >= prop.limit) ? 'upload-disabled-list' : 'upload-mobile-list'
	if (prop.small) {
		className += ' upload-list-small-dxg'
	}
	return className
}
const fileList = ref<UploadUserFile[]>([])
// 图片删除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
	updateModelData()
}
// 图片预览
const handlePreview: UploadProps['onPreview'] = (uploadFile: any) => {
	dialogImageUrl.value =  uploadFile.url || uploadFile?.response?.data
  	dialogVisible.value = true
}
// 上传前大小判断
const beforeAvatarUpload = async (file: any) => {
	const isLt2M = file.size / 1024 / 1024 < 50
	if (!isLt2M) {
		ElMessage.error('上传图片大小不能超过 50MB!')
	}
	return isLt2M
}
// 上传进度（不启用）
const handleProgress = async (evt: any, uploadFile: any, uploadFiles: any) => {
	// console.log(evt.percent.toFixed(2),uploadFile.name);
}
// 上传数量限制
const handleExceed = (files: any, uploadFiles: any) => {
	ElMessage.error(`最多上传${prop.limit}张图片`)
}
// 上传成功
const handleAvatarSuccess = (res: any, file: any) => {
	console.log(res.data);
	if (res.code == 200) {
		updateModelData()
	} else {
		ElMessage.error(res.data || '上传图片错误，请重试')
	}
}
// 清空图片列表
const clearList = (e: any) => {
	fileList.value = []
	updateModelData()
}
// 更新model数据
const updateModelData = () => {
	let imglist = fileList.value.map((i:any)=>{
		return {
			name:i.name,
			url:i.response?.data || i.url || ''
		} || []
	})
	emit('update:modelValue',imglist)
	emit('callback',imglist)
}
// 设置图片列表
const setList = (list: any) => {
	// 示例
	// list = [{
	// 	name:item,
	// 	url:item
	// }]
	fileList.value = list
}
defineExpose({
	uploadRef,
	clearList,
	setList
})
</script>
<style lang="scss" scoped>
	.upload-disabled-list{
		:deep(){
			.el-upload--picture-card{
				display:none!important;
			}
			.el-upload-list__item-preview{
				display:none!important;
			}
			.el-upload-list__item-delete{
				margin-left:0!important;
			}
		}
	}
	.upload-mobile-list{
		:deep(){
			.el-upload-list__item-preview{
				display:none!important;
			}
			.el-upload-list__item-delete{
				margin-left:0!important;
			}
		}
	}
	.upload-list-small-dxg{
		:deep(){
			.el-upload-list__item{
				width: 80px!important;
    			height: 80px!important;
			}
			.el-upload-list__item-thumbnail{
				width: 80px!important;
    			height: 80px!important;
			}
			.el-upload-list__item-actions{
				width: 80px!important;
    			height: 80px!important;
			}
			.el-upload{
				width: 80px!important;
    			height: 80px!important;
			}
			.el-upload-dragger{
				padding: 0!important;
				width: 80px!important;
    			height: 80px!important;
			}
			.el-icon{
				width: 80px!important;
    			height: 80px!important;
			}
		}
	}
</style>
